package servlet;

import model.Blog;
import model.BlogDao;
import model.User;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by xiebang
 * Description
 * User:小谢
 * Date:2022-03-12
 * Time:11:09
 */
@WebServlet("/blog_delete")
public class BolgDeleteServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        resp.setContentType("text/html;charset=utf8");
//      1.先验证用户是否是登录状态,未登录就跳转到登录界面
        User user = Util.checkLogin(req);
        if (user == null){
            System.out.println("当前未登陆");
            resp.sendRedirect("blog_login.html");
            return;
        }
//      2.从请求中读取要删除的博客id
        String blogId = req.getParameter("blogId");
        if (blogId == null || "".equals(blogId)) {
            String html = "<h3>blogId 为空！</h3>";
            resp.getWriter().write(html);
            return;
        }
//      3.获取id后在数据库中检查博客是否存在
        BlogDao blogDao = new BlogDao();
        Blog blog=  blogDao.select(Integer.parseInt(blogId));
        if (blog == null){
            String html = "<h3>数据库中不存在该博客！</h3>";
            resp.getWriter().write(html);
            return;
        }
//      4.如果博客存在 就验证当前用户是否为博客的作者
        if (user.getUserId() != blog.getUserId()){
            String html = "<h3>该用户不是本博客的作者,不能删除</h3>";
            resp.getWriter().write(html);
            return;
        }
//      5.删除博客
        blogDao.deleteBlog(Integer.parseInt(blogId));
//      6跳转至博客页面
        resp.sendRedirect("blog_list");
    }


}
